﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ITAP.ShprossesBuilder.Modelling.Components;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using ITAP.ShprossesBuilder.Utils;
using ITAP.Core.Utils;

namespace ITAP.ShprossesBuilder.Operations {
    public class OperationSaveModelCellToZippedByteArray : IOperation {
        private byte[] zippedModelBytes;

        public byte[] ZippedModelBytes {
            get {
                return zippedModelBytes;
            }
        }
        private int modelId;

        public OperationSaveModelCellToZippedByteArray(int modelId) {
            this.modelId = modelId;
        }
        #region IOperation Members

        public string Name {
            get {
                return "Сохранить модель в массив байт";
            }
        }

        public OperationGroup OperationGroup {
            get {
                return OperationGroup.Other;
            }
        }

        public System.Drawing.Image Thumbnail {
            get {
                return null;
            }
        }

        public void Execute(ModelControl modelControl) {
            foreach(IComponent innerComponent in modelControl.ModelContainer.InnerComponents) {
                if(innerComponent is ModelCell) {
                    ModelCell cell = innerComponent as ModelCell;
                    if(cell.SerialNumber == modelId) {
                        BinaryFormatter formatter = new BinaryFormatter();
                        Stream stream = new MemoryStream();
                        IComponent parent = cell.Parent;

                        cell.Parent = null;

                        formatter.Serialize(stream, cell);

                        cell.Parent = parent;

                        MemoryStream zippedStream = new MemoryStream();
                        Archiver.Zip(stream, zippedStream);
                        zippedStream.Seek(0, SeekOrigin.Begin);
                        zippedModelBytes = new byte[zippedStream.Length];
                        zippedStream.Read(zippedModelBytes, 0, zippedModelBytes.Length);
                        stream.Close();
                        zippedStream.Close();
                        return;
                    }
                }
            }
        }

        public bool CanUndo {
            get {
                return false;
            }
        }

        #endregion
    }
}
